//
//  PublsihAddressViewController.m
//  InviteJob
//
//  Created by chirui on 2017/11/6.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "PublsihAddressViewController.h"

@interface PublsihAddressViewController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource>{
    
    UITableView * _tableView;
    NSMutableArray * _dataArray;
    NSMutableArray * _codeArray;
}


@end

@implementation PublsihAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TitleView(@"地区添加");
    
    _dataArray = @[].mutableCopy;
    _codeArray = @[].mutableCopy;
    
    if (self.meberNameArray.count>0&&self.meberCodeArray.count>0) {
        
        _dataArray = self.meberNameArray;
        _codeArray = self.meberCodeArray;
    }
    
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_public_add" target:self action:@selector(rightBtnClick:)];
    [self creatTableView];
    [self creatSureBtnUI];  
    // picker
    self.pickerView = [[RegionPicker alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64)];
    self.pickerView.pickerView.dataSource = self;
    self.pickerView.pickerView.delegate = self;
    [self.pickerView.confirmButton addTarget:self action:@selector(regionSelectAction) forControlEvents:UIControlEventTouchUpInside];
    [self.pickerView setHidden:YES];
    [self.view addSubview:self.pickerView];
    
}

-(void)rightBtnClick:(UIButton *)btn{
    
    if(!self.province) {
        
        NSString *jsonPath = [[NSBundle mainBundle]pathForResource:@"region_limit" ofType:@"json"];
        NSData *jsonData = [[NSData alloc]initWithContentsOfFile:jsonPath];
        self.province = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
        self.city = self.province[0][@"city"];
        self.country = self.city[0][@"country"];
        self.mem_province = self.province[0][@"province_code"];
        self.mem_city = self.city[0][@"city_code"];
        self.mem_country = self.country[0][@"country_code"];
        //        [_dataArray addObject:[NSString stringWithFormat:@"%@%@%@",self.province[0][@"province_name"], self.city[0][@"city_name"], self.country[0][@"country_name"]]];
        [self.pickerView setHidden:NO];
        [self.pickerView.pickerView reloadAllComponents];
    }else {
        [self.pickerView setHidden:NO];
        [self.pickerView.pickerView reloadAllComponents];
    }
    
}

-(void)creatSureBtnUI{
    
    UIButton * sureBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    sureBtn.frame = CGRectMake(0, HEIGHT-48-64, WIDTH, 48);
    sureBtn.backgroundColor =[UIColor whiteColor];
    [sureBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
    [sureBtn setTitle:@"确 认" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [sureBtn addTarget:self action:@selector(sureBtClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
}

-(void)sureBtClick:(UIButton *)btn{
    
    if (_dataArray.count ==0) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"addressChoose" object:nil userInfo:@{@"addressChoose":@""}];
        SHuiMBhudTextTimeStr(@"请添加服务地区");
        return;
    }
    
    
    NSMutableArray * endArray = [NSMutableArray new];
    
    
    
    for (int i = 0; i<_codeArray.count; i++) {
        
        NSString * str = _codeArray[i];
        NSArray * array = [str componentsSeparatedByString:@" "];
        
        NSString * str_1 = array[0];
        NSString * str_2 = array[1];
        NSString * str_3 = array[2];
        NSString * str_4 = array[3];
        NSString * str_5 = array[4];
        NSString * str_6 = array[5];
        
        
        if ([str_3 isEqualToString:@"0"]) {
            
            if ([str_2 isEqualToString:@"0"]) {
                
                str_3 = str_1;
                str_2 = str_1;
            }else {
            
                str_3 = str_2;
            }
        }
        
        
        if ([str_6 isEqualToString:@"0"]) {
            
            if ([str_5 isEqualToString:@"0"]) {
                
                str_6 = str_4;
                str_5 = str_4;
            }else{
            
                str_6 = str_5;
            }
        }

        NSMutableDictionary * dic = [NSMutableDictionary new];
        [dic setObject:str_1 forKey:@"province_name"];
        [dic setObject:str_2 forKey:@"city_name"];
        [dic setObject:str_3 forKey:@"county_name"];
        [dic setObject:str_4 forKey:@"province"];
        [dic setObject:str_5 forKey:@"city"];
        [dic setObject:str_6 forKey:@"county"];

        [endArray addObject:dic];
 
    }
    
    
    self.block(endArray,_dataArray,_codeArray);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"addressChoose" object:nil userInfo:@{@"addressChoose":@"已添加"}];
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatTableView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-48) style:UITableViewStyleGrouped];
    _tableView.dataSource =self;
    _tableView.delegate =self;
    [self.view addSubview:_tableView];
    //    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    return 50;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return 0.01;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString * iden = @"cellid";
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:iden];
    if (!cell) {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:iden];
    }else{
        while ([cell.contentView.subviews lastObject] != nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.textLabel.text = _dataArray[indexPath.row];
    
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //左滑删除
    return UITableViewCellEditingStyleDelete;
    
}
//修改左滑删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_dataArray.count==1) {
        SHuiMBhudTextTimeStr(@"至少需要一个地区!");
        return;
    }
    
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [_codeArray  removeObjectAtIndex:indexPath.row];
        [_dataArray removeObjectAtIndex:indexPath.row];
        [_tableView reloadData];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        
    }
    
}


// 区域选择确定
- (void)regionSelectAction {
    [self.pickerView setHidden:YES];
    
    
    NSString * codeStr;
    if (self.selectedRegion.length==0) {
        
        //        self.selectedRegion  = @"北京 北京市 东城区";
        codeStr = @"0    ";
        [_dataArray addObject:@"不限    "];
        [_codeArray addObject:[NSString stringWithFormat:@"%@ %@",@"不限    ",@"0    "]];
        
        
    }else{
        [_dataArray addObject:self.selectedRegion];
        codeStr = [NSString stringWithFormat:@"%@ %@ %@",self.mem_province,self.mem_city,self.mem_country];
        [_codeArray addObject:[NSString stringWithFormat:@"%@ %@",self.selectedRegion,codeStr]];
    }
    
    
    [_tableView reloadData];
}

#pragma mark - UIPickerView datasource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            if(![self.province isKindOfClass:[NSNull class]]) {
                return self.province.count;
            }else {
                return 0;
            }
        }
            break;
        case 1:
        {
            if(![self.city isKindOfClass:[NSNull class]]) {
                return self.city.count;
            }else {
                return 0;
            }
        }
            break;
        case 2:
        {
            if(![self.country isKindOfClass:[NSNull class]]) {
                return self.country.count;
            }else {
                return 0;
            }
        }
            break;
        default:
            break;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    switch (component) {
            
        case 0:
        {
            // 省份
            return self.province[row][@"simple_province_name"];
        }
            break;
        case 1:
        {
            // 城市
            return self.city[row][@"simple_city_name"];
        }
            break;
        case 2:
        {
            // 乡镇、街道
            return self.country[row][@"simple_country_name"];
        }
            break;
        default:
            break;
    }
    return nil;
}

#pragma mark - UIPickerView delegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            // 省份
            self.city = self.province[row][@"city"];
            self.country = self.city[0][@"country"];
            [pickerView selectRow:0 inComponent:1 animated:NO];
            [self pickerView:self.pickerView.pickerView didSelectRow:0 inComponent:1];
        }
            break;
        case 1:
        {
            // 城市
            self.country = self.city[row][@"country"];
            [pickerView selectRow:0 inComponent:2 animated:NO];
            [self pickerView:self.pickerView.pickerView didSelectRow:0 inComponent:2];
        }
            break;
        case 2:
        {
            // 乡镇、街道
        }
            break;
        default:
            break;
    }
    
    self.mem_province = self.province[[pickerView selectedRowInComponent:0]][@"province_code"];
    
    
    self.selectedRegion = self.province[[pickerView selectedRowInComponent:0]][@"province_name"];
    
    
    self.mem_city = self.city[[pickerView selectedRowInComponent:1]][@"city_code"];
    
    if ([self.city[[pickerView selectedRowInComponent:1]][@"city_name"] isEqualToString:@"不限"]) {
        self.selectedRegion = [self.selectedRegion stringByAppendingString:@"  "];
    }else{
        self.selectedRegion = [self.selectedRegion stringByAppendingString:[NSString stringWithFormat:@" %@",self.city[[pickerView selectedRowInComponent:1]][@"city_name"]]];
    }
    
    
    
    if([self.country isKindOfClass:[NSArray class]]) {
        self.mem_country = self.country[[pickerView selectedRowInComponent:2]][@"country_code"];
        
        if ([self.country[[pickerView selectedRowInComponent:2]][@"country_name"] isEqualToString:@"不限"]) {
            self.selectedRegion = [self.selectedRegion stringByAppendingString:@"  "];
        }else{
            self.selectedRegion = [self.selectedRegion stringByAppendingString:[NSString stringWithFormat:@" %@",self.country[[pickerView selectedRowInComponent:2]][@"country_name"]]];
        }
        
        
    }else {
        self.mem_country = @"1";
    }
    
    
    
    [pickerView reloadAllComponents];
}


@end
